package com.zmn.oms.zmn.business.impl.work.autoflow.state;

import com.google.common.collect.Lists;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.consts.GlobalConsts;
import com.zmn.cube.common.utils.CollectionUtil;
import com.zmn.oms.business.interfaces.apply.CancelApplyBService;
import com.zmn.oms.business.interfaces.work.OrderWorkListBService;
import com.zmn.oms.business.interfaces.worktrack.WorkTrackBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderDistributeConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.constant.OrderTagConsts;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.bo.work.apply.cancel.CancelApplyResultBO;
import com.zmn.oms.model.dto.graborder.GrabConfigDTO;
import com.zmn.oms.model.dto.work.modify.must.OrderWorkGrabDTO;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.tag.OrderTag;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.tag.OrderTagService;
import com.zmn.oms.zmn.business.interfaces.work.OrderWorkGrabBService;
import com.zmn.oms.zmn.business.interfaces.work.autoflow.state.WorkAutoFlowBService;
import com.zmn.oms.zmn.business.interfaces.work.customwork.ZsDistributeWorkBService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 类描述：抢单分配
 *
 * @author heciqi
 * @date 2019/10/28 20:06
 */
@Slf4j
@Service("flowGrabBService")
public class FlowGrabBServiceImpl<T> implements WorkAutoFlowBService<T> {

    @Resource
    private OrderTagService orderTagService;
    @Resource
    private OrderWorkGrabBService orderWorkGrabBService;
    @Autowired
    private ZsDistributeWorkBService zsDistributeWorkBService;
    @Autowired
    private WorkTrackBService workTrackBService;
    @Autowired
    private OrderWorkListBService orderWorkListBService;
    @Autowired
    private CancelApplyBService cancelApplyBService;
    @Autowired
    private OrderDetailService orderDetailService;

    @Override
    public ResultDTO<T> condition(OrderWork orderWork) {
        if (Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_COMPENSATE)) {
            return ResultDTO.fail("赔偿单不可操作");
        }

        // 不能重复进抢单池
        if (!Objects.equals(orderWork.getGrabType(), GlobalConsts.NONE)) {
            return ResultDTO.fail("已经进过抢单池");
        }

        // 只有啄木鸟平台参与抢单
        if (!Objects.equals(orderWork.getPlatWork(), GlobalConsts.PLAT_MARK_ZMN)) {
            return ResultDTO.fail("仅允许啄木鸟工单进抢单池");
        }

        // 只允许新单进抢单池
        if (!Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_NEW)) {
            return ResultDTO.fail("返修单/退款单不能进抢单池");
        }

        // 工程师加单不能自动进抢单池
        if (NumberUtil.isNotNullOrZero(orderWork.getRecommenderId()) && Objects
                .equals(com.zmn.common.constant.GlobalConsts.OPERATE_USER_TYPE_MASTER, orderWork.getRecommenderType())) {
            return ResultDTO.fail("工程师加单不能自动进抢单池");
        }

        // 结果：已分单 - 进行中，可操作
        List<Integer> supportStatusList = Lists.newArrayList(OrderStatusConsts.WORK_STATUS_ASSIGN);

        // 是否网格化派单
        boolean isGrid = zsDistributeWorkBService.isGridDistribute(orderWork);
        if (isGrid){
            supportStatusList.add(OrderStatusConsts.WORK_STATUS_CONFIRM);
        }

        List<Integer> supportResultStatusList = Lists.newArrayList(OrderStatusConsts.WORK_RESULT_DOING);
        boolean resultStatusSupport = supportResultStatusList.contains(orderWork.getResultStatus());
        boolean statusSupport = supportStatusList.contains(orderWork.getStatus());

        if (!statusSupport) {
            return ResultDTO.fail("不是已确认或已分单状态");
        }

        if (!resultStatusSupport) {
            return ResultDTO.fail("不是进行中状态");
        }

        // 已派单过的，不需要处理
        if (orderWork.getStatus() >= OrderStatusConsts.WORK_STATUS_DISTRIBUTE) {
            return ResultDTO.fail("已派单过");
        }

        // 待取消，不允许自动派单
        Integer waitCancelStatus = workTrackBService.getUserWaitCancelStatus(orderWork.getOrderId(), orderWork.getWorkId());
        if (Objects.equals(waitCancelStatus, GlobalConsts.YES)) {
            return ResultDTO.fail("用户申请取消，不可操作");
        }

        CancelApplyResultBO cancelApplyResultBO = cancelApplyBService.getWaitCancelInfo(orderWork.getOrderId(), orderWork.getWorkId());
        if (Objects.equals(cancelApplyResultBO.getUserWaitCancelStatus(), GlobalConsts.YES)) {
            return ResultDTO.fail("用户申请取消，不可操作");
        }

        if (!Objects.equals(orderWork.getStatus(), OrderStatusConsts.WORK_STATUS_ASSIGN)) {
            // 是否网格化派单
            boolean isGirdId = zsDistributeWorkBService.isGridDistribute(orderWork);
            if (isGirdId) {
                if (!Objects.equals(orderWork.getStatus(), OrderStatusConsts.WORK_STATUS_CONFIRM)) {
                    return ResultDTO.fail("未确认");
                }
            } else {
                return ResultDTO.fail("未分单");
            }
        }

        // 高价值用户订单必须手动派单
        List<OrderTag> orderTagList = orderTagService.listOrderTagByOrderId(orderWork.getOrderId(), orderWork.getWorkId());
        if (CollectionUtil.isNotNullOrEmpty(orderTagList)) {
            boolean highValueUser = orderTagList.stream()
                    .anyMatch(tag -> Objects.equals(tag.getTagType(), OrderTagConsts.ORDER_TAG_USER_SYSTEM) &&
                            (Objects.equals(tag.getTagId(), OrderTagConsts.USER_TAG_ID_HIGH_VALUE) || Objects.equals(tag.getTagId(), OrderTagConsts.TAG_ID_HIGH_VALUE_USER)));
            if (highValueUser) {
                return ResultDTO.fail("高价值用户订单必须手动派单");
            }

            // 无网格订单不允许进普通抢单池
            boolean nonGridGrab = orderTagList.stream().anyMatch(tag -> Objects.equals(tag.getTagId(),
                    OrderTagConsts.TAG_ID_NON_GRID));
            if (nonGridGrab) {
                return ResultDTO.fail("无网格订单不允许进普通抢单池");
            }
        }

        // vVip用户 平台指派
        if (Objects.equals(orderWork.getDistributeWay(), OrderDistributeConsts.DISTRIBUTE_WAY_PLAT)) {
            OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(orderWork.getOrderId());
            if (Objects.nonNull(orderDetail)) {
                if (Objects.equals(orderDetail.getVvip(), GlobalConsts.YES)) {
                    return ResultDTO.fail("VVIP用户订单必须手动派单");
                }
            }
        }

        try {
            // 抢单类型逻辑判断
            GrabConfigDTO grabConfigDTO = orderWorkGrabBService.grabConfig(orderWork);
            OrderWorkGrabDTO orderWorkGrabDTO = new OrderWorkGrabDTO();
            orderWorkGrabDTO.setOrderId(orderWork.getOrderId());
            orderWorkGrabDTO.setWorkId(orderWork.getWorkId());
            orderWorkGrabDTO.setGrabType(GlobalConsts.YES);
            orderWorkGrabDTO.setAgent(grabConfigDTO.getAgent());
            orderWorkGrabDTO.setGrabEndTime(grabConfigDTO.getGrabEndTime());
            orderWorkGrabDTO.setAutoFlow(false);
            return ResultDTO.success(orderWorkGrabDTO);
        } catch (OmsBaseException e) {
            return ResultDTO.fail(e.getMessage());
        }

        /*if (orderWork.getChannelId() != 1027) {
            return ResultDTO.fail("非测试渠道");
        }*/
    }

    @Override
    public void execute(T o) {
        try {
            orderWorkGrabBService.saveGrabType((OrderWorkGrabDTO) o);
        } catch (Exception e) {
            log.error("自动分配抢单异常" + e.getMessage(), e);
        }
    }

}
